import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/pre_check_in/api.dart';
import 'package:ct_pa_majordomo/pages/apartment/api.dart';
import 'package:ct_pa_majordomo/widgets/button/index.dart';
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import 'package:ct_pa_majordomo/widgets/tai_dialog/index.dart';
import 'package:ct_pa_majordomo/utils/stacker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:ct_pa_majordomo/pages/pre_check_in/utils/status.dart';
import 'package:ct_pa_majordomo/router/keys.dart';

class PreCheckInAudit extends StatefulWidget {
  final int registerId;
  final bool isAudit;

  const PreCheckInAudit({
    super.key,
    required this.registerId,
    this.isAudit = false,
  });

  @override
  State<PreCheckInAudit> createState() => _PreCheckInAuditState();
}

class _PreCheckInAuditState extends State<PreCheckInAudit> {
  Map<String, dynamic> _detail = {};
  String _rejectReason = "";
  bool _loading = false;
  List _renterList = [];
  Map<String, dynamic> mainRenter = {};
  List otherRenters = [];
  Map<String, dynamic> _roomInfo = {};

  @override
  void initState() {
    super.initState();
    _fetchDetail();
  }

  Future<void> _fetchDetail() async {
    setState(() {
      _loading = true;
    });
    try {
      Map resData = await preCheckInApi.getPreCheckInDetail(widget.registerId);
      setState(() {
        _detail = resData["data"] ?? {};
        _renterList = _detail["renterList"] ?? [];
        // 尝试找到主租户，如果找不到则是空Map
        var foundMainRenter = _renterList.firstWhere(
          (renter) => renter["mainFlag"] == "1",
          orElse: () => <String, dynamic>{},
        );
        mainRenter = foundMainRenter;
        otherRenters = _renterList.where((renter) => renter["mainFlag"] == "2").toList();
        _roomInfo = _detail["room"] ?? {};
      });
      
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }


  // 获取房间显示名称
  String _getRoomDisplayName(Map item) {
    String name = item["name"] ?? "";
    String buildingName = item["buildingName"] ?? "";
    String fullName = "$buildingName$name";
    return fullName.isNotEmpty ? fullName : "暂未登记房间";
  }

  // 审核操作
  void _handleAudit({bool pass = true}) {
    if (!widget.isAudit) return;
    
    taiDialog(
      context: context,
      title: pass ? "通过" : "驳回",
      contentPadding: EdgeInsets.zero,
      child: !pass
          ? Dialog(
              child: TextFormField(
                autofocus: true,
                textAlign: TextAlign.center,
                decoration: const InputDecoration(
                  hintText: "请输入驳回原因",
                  hintStyle: TextStyle(color: ThemeVars.colorTextTer),
                  border: InputBorder.none,
                  filled: true,
                  fillColor: ThemeVars.colorBackground,
                ),
                onChanged: (value) {
                  setState(() {
                    _rejectReason = value;
                  });
                },
              ),
            )
          : const Padding(
              padding: EdgeInsets.all(16),
              child: Text("确定通过审核?"),
            ),
      onCancel: (BuildContext context) {
        Stacker.pop(context);
      },
      onConfirm: (BuildContext context) async {
        if (!pass && _rejectReason.isEmpty) {
          EasyLoading.showToast("请输入驳回原因");
          return;
        }

        try {
          EasyLoading.show(status: "处理中...");
          await preCheckInApi.auditPreCheckIn(
            widget.registerId,
            {
              "auditStatus": pass ? 1 : 2,
              if (!pass) "auditComment": _rejectReason,
            },
          );

          EasyLoading.dismiss();
          EasyLoading.showSuccess("操作成功");
          Stacker.pop(); // 关闭弹窗
          Stacker.pop(true); // 返回上一页并传递更新标志
        } catch (e) {
          EasyLoading.dismiss();
          EasyLoading.showError("操作失败");
          print(e);
        }
      },
    );
  }

  Widget _buildRenterCard(Map<String, dynamic> renter, bool isMainRenter) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                decoration: BoxDecoration(
                  color: isMainRenter
                      ? ThemeVars.colorPrimaryLight
                      : ThemeVars.colorWarningLight,
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  isMainRenter ? "承租人" : "同住人",
                  style: TextStyle(
                    color: isMainRenter
                        ? ThemeVars.colorPrimary
                        : ThemeVars.colorWarning,
                    fontSize: 12,
                  ),
                ),
              ),
              if (_detail['status'] == PreCheckInStatus.CHECKED_IN)
                Button(
                  type: ButtonType.primary,
                  size: ButtonSize.small,
                  onPressed: () {
                    Stacker.pushNamed(
                      Keys.DEVICE_LOCK_ADD_IC_CARD,
                      arguments: {
                        'renter': renter,
                        'lockId': 2,
                      },
                    ).then((value) {
                      if (value == true) {
                        EasyLoading.showSuccess('发卡成功');
                      }
                    });
                  },
                  child: const Text('发卡'),
                ),
            ],
          ),
          const SizedBox(height: 12),
          Text("房客类型：${renter['renterType'] == '1' ? '省内' : '省外'}"),
          const SizedBox(height: 12),
          Text("姓名：${renter['name'] ?? '--'}"),
          const SizedBox(height: 8),
          Text("联系方式：${renter['contacts'] ?? '--'}"),
          const SizedBox(height: 8),
          Text("身份证号：${renter['idCardNumber'] ?? '--'}"),
          if (renter['picUrl'] != null && renter['picUrl'].toString().isNotEmpty) ...[
            const SizedBox(height: 12),
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Image.network(
                renter['picUrl'],
                width: 120,
                height: 160,
                fit: BoxFit.cover,
              ),
            ),
          ],
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: widget.isAudit ? "预登记审核" : "预登记详情",
      child: _loading
          ? const Center(child: CircularProgressIndicator())
          : Stack(
              children: [
                ListView(
                  padding: const EdgeInsets.all(16),
                  children: [
                    if (_detail['status'] != null) ...[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          PreCheckInStatus.buildStatusTag(_detail['status'].toString()),
                        ],
                      ),
                      const SizedBox(height: 16),
                    ],
                    // 房间信息卡片
                    if (_roomInfo.isNotEmpty) ...[
                      Container(
                        margin: const EdgeInsets.only(bottom: 16),
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(8),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.05),
                              blurRadius: 4,
                              offset: const Offset(0, 2),
                            ),
                          ],
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                                                 Container(
                                   padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                                   decoration: BoxDecoration(
                                     color: ThemeVars.colorPrimaryLight,
                                     borderRadius: BorderRadius.circular(4),
                                   ),
                                   child: const Text(
                                     "房间信息",
                                     style: TextStyle(
                                       color: ThemeVars.colorPrimary,
                                       fontSize: 12,
                                     ),
                                   ),
                                 ),
                              ],
                            ),
                            const SizedBox(height: 12),
                            Text("房间名称：${_getRoomDisplayName(_roomInfo)}"),
                          ],
                        ),
                      ),
                    ],
                    if (mainRenter.isNotEmpty) _buildRenterCard(mainRenter, true),
                    ...otherRenters.map((renter) => _buildRenterCard(renter, false)),
                    // 底部留白，防止按钮遮挡
                    if (widget.isAudit) const SizedBox(height: 80),
                  ],
                ),
                if (widget.isAudit && _detail['status'] == PreCheckInStatus.PENDING)
                  Positioned(
                    left: 16,
                    right: 16,
                    bottom: 16,
                    child: Row(
                      children: [
                        Expanded(
                          child: Button(
                            type: ButtonType.danger,
                            onPressed: () => _handleAudit(pass: false),
                            child: const Text("驳回"),
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: Button(
                            onPressed: () => _handleAudit(pass: true),
                            child: const Text("通过"),
                          ),
                        ),
                      ],
                    ),
                  ),
              ],
            ),
    );
  }
}
